package online.hxstart.code.concurrent.chapter12;

import java.util.concurrent.TimeUnit;

/**
 * @author huxing
 * @date 2019/7/12 星期五 20:09
 * @describe
 */
public class VolatileFoo {

  private static final int MAX = 5;
  private static volatile int init_value = 0;

  public static void main(String[] args) {

    new Thread(
        () -> {
          int localValue = init_value;
          while (localValue < MAX) {

            if (init_value != localValue) {
              System.out.printf("The init_value is update to [%d]\n", init_value);
              localValue = init_value;
            }
          }
        },
        "Reader")
        .start();

    new Thread(
        () -> {
          int localValue = init_value;

          while (localValue < MAX) {
            System.out.printf("The  init_value will be changed to [%d] \n", ++localValue);
            init_value = localValue;
            try {
              TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }
        },
        "Updater")
        .start();
  }
}
